<!--文件信息管理页面-->
<template>
  <div class="edu-page-warp">
    <!-- 列表查询条件 -->
    <condition-card @reset="reset" @search="onSubmit(false)">
      <el-form ref="queryForm" label-suffix="：" :model="queryForm" label-position="right" label-width="130px">
        <el-row v-if="global.isAdmin || global.isAcdemicDean">
          <el-col :span="8">
            <el-form-item :label="$t('fileManage.manageDept')">
              <el-select v-model="queryForm.manageDeptId" style="width: 100%" clearable filterable :placeholder="$t('common.text.all')"
                         @change="manageDeptChange(queryForm.manageDeptId,queryForm.roleId,true)">
                <el-option v-for="item in options.manageDeptIds" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('fileManage.role')">
              <el-select v-model="queryForm.roleId" style="width: 100%" clearable filterable :placeholder="$t('common.text.all')"
                         @change="roleChange(queryForm.manageDeptId,queryForm.roleId,true)" >
                <el-option v-for="item in options.roles" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('fileManage.group')">
              <el-select v-model="queryForm.groupId" style="width: 100%" clearable filterable :placeholder="$t('common.text.all')">
                <el-option v-for="item in options.groups" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('fileManage.moduleName')">
              <el-select v-model="queryForm.moduleId" style="width: 100%" clearable filterable :placeholder="$t('common.text.all')">
                <el-option v-for="item in options.modules" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </condition-card>
    <!--列表信息-->
    <el-card shadow="never">
      <div class="edu-page-title">{{$t('fileManage.fileList')}}</div>
      <el-row style="margin-bottom:16px">
        <el-col :span="24">
          <div class="float-left">
            <KeywordInput v-model="queryForm.keyword" :placeholder="$t('fileManage.keyWordTips')" @enter="onSubmit(true)"></KeywordInput>
          </div>
          <div class="float-right">
            <el-button type="primary" v-if="global.isAdmin || global.isAcdemicDean" @click="handleAdd">{{$t('fileManage.btns.add')}}</el-button>
            <el-button type="primary" @click="handleBatchDownload">{{$t('fileManage.btns.batchDownload')}}</el-button>
            <el-button type="primary" v-if="global.isAdmin || global.isAcdemicDean" @click="handleBatchDelete">{{$t('fileManage.btns.batchDelete')}}</el-button>
          </div>
        </el-col>
      </el-row>
      <edu-table :url="tableApi" ref="mainTable" size="mini" :orderFixed="true" style="width:100%" @selection-change="selectionChange">
        <el-table-column :label="$t('fileManage.fileName')" width="160" fixed="left" show-overflow-tooltip>
          <template slot-scope="scope">
            <!--点击文件名称预览文件-->
            <el-button @click="handlePreview(scope.row)" type="text">{{scope.row.fileName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column :label="$t('fileManage.filePurposes')" prop="filePurposes" min-width="140" show-overflow-tooltip/>
        <el-table-column :label="$t('fileManage.manageDept')"  prop="manageDeptIdI18n" width="110" show-overflow-tooltip/>
        <el-table-column :label="$t('fileManage.role')" prop="roleIdI18n" width="90" show-overflow-tooltip/>
        <el-table-column :label="$t('fileManage.group')" prop="groupName" min-width="150" show-overflow-tooltip/>
        <el-table-column :label="$t('fileManage.moduleName')" prop="moduleName" min-width="150" show-overflow-tooltip/>
        <el-table-column :label="$t('fileManage.fileType')" prop="fileType" width="80"/>
        <el-table-column :label="$t('fileManage.fileSize')" prop="fileSize" width="90">
          <template slot-scope="scope">
            <label>{{ getFileSize(scope.row.fileSize) }}</label>
          </template>
        </el-table-column>
        <!--<el-table-column :label="$t('fileManage.remark')" prop="remark" width="160"></el-table-column>-->
        <el-table-column :label="$t('message.operating')" fixed="right" width="140">
          <!--下载、查看、删除-->
          <template slot-scope="scope">
            <el-button type="text" @click="handleDownload(scope.row.filePath)">
              {{$t('fileManage.btns.download')}}
            </el-button>
            <el-button type="text" @click="handleView(scope.row)">
              {{$t('fileManage.btns.view')}}
            </el-button>
            <el-button type="text" v-if="global.isAdmin || global.isAcdemicDean" @click="handleDelete(scope.row)">
              {{$t('fileManage.btns.delete')}}
            </el-button>
          </template>
        </el-table-column>
      </edu-table>
    </el-card>

    <!-- 新增、查看 -->
    <edu-dialog ref="dialogModel" :title="dialogTitle" width="800px" :autoHeight="true" :showFooter="false">
      <el-form ref="dialogFrom" :model="modelData" :rules="modelRules" label-position="right" label-width="190px" label-suffix="：">
        <!--文件用途、管理部门、应用角色、用户组、模块名称、备注、附件-->
        <el-row :gutter="24">
          <!--文件用途 -->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.filePurposes')" prop="filePurposes">
              <template>
                <el-input :disabled="this.modelFlag == 'view'" v-model="modelData.filePurposes" maxlength="64" :placeholder="$t('inputPlaceholder')"/>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <!--管理部门 -->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.manageDept')" prop="manageDeptId">
              <template>
                <el-select style="width:100%" v-model="modelData.manageDeptId" clearable filterable :disabled="this.modelFlag == 'view'"
                           @change="manageDeptChange(modelData.manageDeptId,modelData.roleId,false)">
                  <el-option v-for="item in modelOptions.manageDeptIds" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <!--应用角色 -->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.role')" prop="roleId">
              <template>
                <el-select style="width:100%" v-model="modelData.roleId" clearable filterable :disabled="this.modelFlag == 'view'"
                           @change="roleChange(modelData.manageDeptId,modelData.roleId,false)">
                  <el-option v-for="item in modelOptions.roles" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <!--用户组 -->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.group')">
              <template>
                <el-select style="width:100%" v-model="modelData.groupIds" clearable filterable multiple :disabled="this.modelFlag == 'view'">
                  <el-option v-for="item in modelOptions.groups" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <!--模块 -->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.moduleName')" prop="moduleId">
              <template>
                <el-select style="width:100%" v-model="modelData.moduleId" clearable filterable :disabled="this.modelFlag == 'view'">
                  <el-option v-for="item in modelOptions.modules" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24"  v-if="this.modelFlag == 'view'">
          <!--查看时展示上传者信息 -->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.uploadPersonal')">
              <template>
                <el-input :disabled="this.modelFlag == 'view'" v-model="modelData.creator"></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.uploadTime')">
              <template>
                <el-input :disabled="this.modelFlag == 'view'" v-model="modelData.createTime"></el-input>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <!--备注 -->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.remark')">
              <el-input :disabled="this.modelFlag == 'view'" v-model="modelData.remark" type="textarea" rows="3" maxlength="255" :placeholder="$t('inputPlaceholder')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="this.modelFlag != 'view'">
          <!--附件上传-->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.attachment')" prop="fileUrl">
              <el-upload
                ref="uploadBtn"
                :auto-upload="false"
                action="/api/commonservice/obsfile/uploadfile"
                :data="{bucketname: 'face', folderpath: 'file'}"
                :limit="1"
                :on-change="handleUploadChange"
                :on-exceed="handleExceed" :on-remove="handleUploadChange"
                :on-success="handleUploadSuccess">
                <el-button size="small" type="primary">{{$t('common.btn.clickUpload')}}</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="this.modelFlag == 'view'">
          <!--附件下载-->
          <el-col :span="20">
            <el-form-item :label="$t('fileManage.attachment')">
              <el-button type="text" @click="handleDownload(modelData.filePath)" style="display:block;">{{modelData.fileName}}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span class="float-right">
        <el-button @click="modelCancel">{{$t("common.btn.cancel")}}</el-button>
        <el-button @click="modelSave" type="primary" v-if="this.modelFlag === 'add'">{{$t('common.btn.confirm')}}</el-button>
      </span>
    </edu-dialog>

    <el-dialog :title="viewTitle" :visible.sync="picDialogVisible" width="50%">
      <img :src="'api/commonservice/obsfile/downloadfile?objectkey=' + picUrl" alt="" width="100%">
      <span slot="footer" class="dialog-footer">
            <el-button @click="picDialogVisible=false">取消</el-button>
        </span>
    </el-dialog>


  </div>
</template>

<script>
    import axios from 'axios'
    import {queryDic} from "common/src/api/dictionary";
    import UTILS from "common/src/utils/utils";
    import {getGroups} from 'common/src/api/user'
    import {
        findAllInfoAuthByUserId,//查询菜单信息
        FileManageTableList,//列表查询
        getDetail,//获取详情
        batchDelete,//删除（批量删除）
        addFile,//添加文件
        batchDownload,//批量下载
        fileToByteArray
    } from "common/src/api/fileManage/fileManage.js";
    import PreviewOffice from "common/src/components/common/PreviewOffice.vue"
    import mixin from 'common/src/mixins/index';
    export default {
        name: 'fileManage',
        mixins: [mixin],
        components: {PreviewOffice},
        data() {
            return {
                viewTitle:'',
                picDialogVisible:false,
                picUrl:'',
                fileUrl:'',
                showDoc:false,
                tableApi: FileManageTableList,
                newFileList:[],
                queryForm: {
                    manageDeptId: null, //管理部门
                    moduleId: null, //模块名称
                    roleId: null, //角色
                    groupId: null, //用户组
                    keyword: null, //关键字
                },
                options: {
                    manageDeptIds: [],//管理部门
                    roles: [],//应用角色
                    groups: [],//用户组
                    modules: [],//模块名称
                },
                modelOptions: {
                    manageDeptIds: [],//管理部门
                    roles: [],//应用角色
                    groups: [],//用户组
                    modules: [],//模块名称
                },
                selectInfos: [],//列表勾选记录
                modelFlag: null,
                dialogTitle:null,
                //新增、查看弹框属性
                modelData: {
                    id: null,
                    filePurposes: null,//文件用途
                    manageDeptId: null,//管理部门
                    roleId: null,//角色ID
                    groupIds: [],//用户组ID集合
                    moduleId: null,//模块ID
                    remark: null,//备注
                    filePath: null,//文件路径
                    creator:null,
                },
                fileList: [],//上传文件
                modelRules: {
                    filePurposes: [
                        {
                            required: true,
                            message: "请填写文件用途",
                            trigger: "change"
                        },
                        { min: 0, max: 64, message: this.$t('fileManage.filePurposesTips'), trigger: 'change' }
                    ],
                    manageDeptId: [
                        {
                            required: true,
                            message: "请选择管理部门",
                            trigger: "change"
                        }
                    ],
                    roleId: [
                        {
                            required: true,
                            message: "请选择应用角色",
                            trigger: "change"
                        }
                    ],
                    /*groupIds: [
                        {
                            type:"array",
                            required: true,
                            message: "请选择用户组",
                            trigger: "change"
                        }
                    ],*/
                    moduleId: [
                        {
                            required: true,
                            message: "请选择模块名称",
                            trigger: "change"
                        }
                    ],// 附件
                    fileUrl: [
                        { required: true, validator: (rule, value, callback)=>this.validateFile(rule, value, callback, 'uploadBtn'), trigger: 'change' },
                    ]

                },
            };
        },
        created() {
        },
        mounted() {
            this.init();
        },
        methods: {
            //列表文件大小转换
            getFileSize(size){
                //默认字节，做单位换算
                if(size < 1024){
                    return size + ' B'
                }else if(size >= 1024 && size < 1024 * 1024){
                    return (size / 1024).toFixed(1) + ' K'
                }else if(size >= 1024 * 1024 && size < 1024 * 1024 * 1024){
                    return (size / 1024 / 1024).toFixed(1) + ' M'
                }else if(size >= 1024 * 1024 * 1024){
                    return (size / 1024 / 1024 / 1024).toFixed(1) + ' G'
                }
            },

            // 校验上传文件
            validateFile (rule, value, callback, uploadRef) {
                if (!this.fileList.length > 0) {
                    //this.$refs[uploadRef].uploadFiles.length
                    return callback(new Error(this.$t('fileManage.emptyFileTips')));
                } else {
                    return callback();
                }
            },

            //预览文件
            async handlePreview(row) {
                this.viewTitle = "文件预览"
                let fileInfo = _.cloneDeep(row)
                let file = {name:fileInfo.fileName,url:fileInfo.filePath}
                if(file.name && file.url) {
                    if((file.name).includes('.jpeg') ||(file.name).includes('.jpg') || (file.name).includes('.png') || (file.name).includes('.bmp')) {
                        this.viewTitle  += "（" + fileInfo.fileName +"）"
                        this.picUrl = file.url
                        this.picDialogVisible = true
                    } else if((file.name).includes('.rar') || (file.name).includes('.zip')|| (file.name).includes('.7z')) {
                        this.$message.error("该类型文件暂不支持预览!")
                    } else {
                        const resp = await fileToByteArray(file)
                        if (resp.code === 200) {
                            let data = {
                                originalFileName: resp.data.originalFileName,
                                content: resp.data.content
                            }
                            // 文件从obs转换到预览服务过程2：预览服务接收文件字节数组
                            const response = await axios.post(window.location.origin + '/filePre/fileImport', data, {
                                headers: { 'X-Token': localStorage.getItem('sessionid') || '' }
                            })
                            if (response.data.code === 200) {
                                let lspdfUrl =
                                    window.location.origin + '/filePre/onlinePreview?url=' +
                                    window.location.origin + '/filePre/demo/' +
                                    resp.data.originalFileName
                                window.open(lspdfUrl)
                            }
                        }
                    }
                } else {
                    this.$message.error("文件损坏!")
                }
            },

            //页面数据初始化
            init() {
                //学生和教师直接查询权限信息
                if(this.global.isStudent){
                  this.manageDeptChange(this.global.currentUser.currentManageDptId,null,true);
                }
                else if(this.global.isAnyTeacher){
                    this.manageDeptChange(null,null,true);
                }else{
                    let data = {
                        lang: this.$store.getters.language || "cn",
                        type: "allChild",
                        keys: ["X_GLBM","X_NZYHJS"]
                    };
                    queryDic(data).then(res => {
                        if (res.code == 200 && res.data) {
                            UTILS.fillSelect({manageDeptIds: "X_GLBM",roles:"X_NZYHJS"}, res.data, this.options);
                            UTILS.fillSelect({manageDeptIds: "X_GLBM",roles:"X_NZYHJS"}, res.data, this.modelOptions);
                        }
                    });
                    this.queryForm.manageDeptId = this.global.currentUser.currentManageDptId;
                }

                //查询列表
                this.onSubmit(true)
            },


            //管理部门变更
            manageDeptChange(manageDeptId,roleId,isQuery){
                let param = this.getQueryMenuParam(roleId)

                let query = 'userId=' + this.global.currentUser.uid + '&type=1' + '&roleType=' + param.roleType + '&currentManageDptId=' + manageDeptId
                findAllInfoAuthByUserId(query).then(res => {
                    let modules = []
                    //角色老师--教师服务(8617)、本科生导师服务(8616)、研究生导师服务(8615)
                    let teacherModule = [8617,8616,8615]
                    if (res.code === 200 && res.data) {
                        let menuList = res.data;
                        menuList.forEach(menu => {
                            if(menu.parentAuthId === -1 && !teacherModule.includes(menu.authId)){
                                modules.push({label: menu.authNameCh, value: menu.authId})
                            }

                            if(menu.parentAuthId === 8617){
                                modules.push({label: menu.authNameCh + '-教师服务', value: menu.authId})
                            }
                            if((!manageDeptId  ||  manageDeptId === '1') && menu.parentAuthId === 8616){
                                modules.push({label: menu.authNameCh + '-本科生导师服务', value: menu.authId})
                            }
                            if((!manageDeptId  || manageDeptId !== '1') && menu.parentAuthId === 8615){
                                modules.push({label: menu.authNameCh + '-研究生导师服务', value: menu.authId})
                            }
                        });

                        if(isQuery){
                            this.options.modules = modules
                        }else{
                            if(this.modelFlag === 'add'){
                                this.modelData.moduleId = null
                            }
                            this.modelOptions.modules = modules
                        }
                    }
                }).catch(error => {
                    console.log("获取用户权限接口异常",error)
                })
            },

            //封装查询菜单的参数
            getQueryMenuParam(roleId){
                let param = {roleType: roleId}
                switch(roleId){
                    case '1':
                    case '2':
                        param.roleType = 1;
                        break;
                    case '3':
                    case '4':
                    case '5':
                        param.roleType = 2;
                        break;
                    case '6':
                        param.roleType = 3;
                        break;
                    default:
                        param.roleType = null
                }

                if(!param.roleType){
                    if(this.global.isStudent){
                        param.roleType = 3;
                    }else if(this.global.isAnyTeacher){
                        param.roleType = 2;
                    }else{
                        param.roleType = 1;
                    }
                }
                return param;
            },

            //角色变更(根据角色信息获取模块信息和用户组信息)
            roleChange(manageDeptId,roleId,isQuery){
                //重新获取模块名称
                this.manageDeptChange(manageDeptId,roleId,isQuery)

                if(!roleId){
                    return
                }
                //获取用户组信息
                let request={pageNum_: 1,pageSize_: 1000,innerRole: roleId}
                getGroups(request).then((resp) => {
                    let groups=[]
                    if (resp.code === 200 && resp.data && resp.data.list) {
                        resp.data.list.forEach(item => {
                            groups.push({label: item.groupName, value: item.groupId})
                        })
                        if(isQuery){
                            this.options.groups=groups
                        }else{
                            if(this.modelFlag === 'add'){
                                this.modelData.groupIds = []
                            }
                            this.modelOptions.groups=groups
                        }
                    }
                }).catch(error => {
                    console.log("获取用户组接口异常",error)
                })
            },

            //列表查询
            onSubmit(refresh) {
                if(refresh){
                    this.$refs.mainTable.pageNum = 1;
                }
                if(this.queryForm.keyword){
                    let param = {keyword: this.queryForm.keyword}
                    this.$refs.mainTable.search(param);
                }else{
                    let param = _.cloneDeep(this.queryForm)
                    param.keyword=null
                    this.$refs.mainTable.search(param);
                }
            },

            //列表重置
            reset() {
                Object.keys(this.queryForm).forEach(key => {
                    this.queryForm[key] = null;
                });
                this.$refs.mainTable.pageNum = 1;
                //查询列表
                if(this.global.isAdmin || this.global.isAcdemicDean){
                    this.queryForm.manageDeptId = this.global.currentUser.currentManageDptId;
                }
                this.$refs.mainTable.search(this.queryForm);
            },

            //列表数据勾选
            selectionChange(val) {
                this.selectInfos = val;
            },

            //清空弹框对象
            clearModelData() {
                //移除表单校验
                if(this.$refs.dialogFrom){
                    this.$refs.dialogFrom.resetFields();
                }
                for (let key in this.modelData) {
                    this.modelData[key] = null;
                }
                this.modelData.groupIds=[]
                this.fileList = [];
            },

            //新增
            handleAdd() {
                this.modelFlag = "add";
                this.dialogTitle = this.$t('fileManage.btns.add');
                this.clearModelData();
                //查询列表
                if(this.global.isAdmin || this.global.isAcdemicDean){
                    this.modelData.manageDeptId = this.global.currentUser.currentManageDptId;
                }
                this.$refs.dialogModel.open();
                if(this.$refs.uploadBtn){
                    this.$refs.uploadBtn.clearFiles()
                }
                this.roleChange(this.modelData.manageDeptId,this.modelData.roleId,false)

            },

            handleBatchDelete(){
                if (this.selectInfos == null || this.selectInfos.length == 0) {
                    this.$message({type: "error", message: this.$t('fileManage.selectTips')});
                    return;
                }
                let param = this.selectInfos.map(obj => {return obj.id;})
                this.$delConfirm().then(() => {
                    batchDelete(param).then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.$t('common.tips.deleteSuccess'));
                            this.reset();
                        }
                    });
                }).catch(error => {
                    console.log("文件管理_批量删除异常",error)
                });
            },

            //批量下载
            handleBatchDownload(){
                let param = _.cloneDeep(this.queryForm);
                param.ids = this.selectInfos.map(v=>v.id);
                batchDownload(param);
            },

            //单文件下载
            handleDownload(filePath) {
                if(!filePath){
                    this.$message.error(this.$t('fileManage.fileNotExist'));
                }
                window.location.href = "/api/commonservice/obsfile/downloadfile?objectkey=" + filePath;
            },

            //查看
            handleView(row) {
                this.fileList = [];
                this.clearModelData();
                this.modelFlag = "view";
                this.dialogTitle = this.$t('fileManage.btns.view');
                getDetail(row.id).then(res => {
                    if (res.code == 200) {
                        let fileInfo = res.data;
                        let file = {name: fileInfo.fileName, url: fileInfo.filePath};
                        this.fileList.push(file);
                        this.modelData = fileInfo;
                        this.modelData.roleId = fileInfo.roleId.toString()
                        this.modelData.groupIds = [fileInfo.groupId]
                        this.roleChange(this.modelData.manageDeptId,this.modelData.roleId)
                        this.modelData.creator = fileInfo.createUser +  '（' + fileInfo.createId + '）'
                        this.$refs.dialogModel.open();
                    }
                });
            },

            //删除
            handleDelete(row) {
                this.$delConfirm().then(() => {
                    batchDelete([row.id]).then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.$t('common.tips.deleteSuccess'));
                            this.reset();
                        }
                    });
                }).catch(error => {
                    console.log("文件管理_删除异常",error)
                });
            },


            //导入前对文件进行校验
            handleUploadChange(file, fileList) {
                if (fileList.some(file => file.size / 1024 / 1024 > 10)) {
                    this.$message.error("上传附件大小不能超过10MB");
                    fileList = fileList.filter(
                        file => file.status === "success" ? true : (file.size / 1024 / 1024 <= 10)
                    );
                }
                let len = fileList.length;
                const types = [".txt",".zip", ".rar", ".jpeg", ".jpg", ".png", ".bmp", ".doc", ".docx",".xlsx", ".xls",".pdf"];
                fileList = fileList.filter(file => {
                    let index = file.name.lastIndexOf(".");
                    if (index == -1) return false;
                    let type = file.name.substring(index).toLowerCase();
                    return types.includes(type);
                });
                if (len != fileList.length) {
                    this.$message({type: "error", message: this.$t('auditReport.tip.attachment_upload')});
                }
                this.fileList = fileList;
            },
            //文件上传失败，弹出失败提示
            handleUploadError(err) {
                this.$message({type: "error", message: err});
            },
            //文件上传个数限制
            handleExceed(files, fileList) {
                this.$message.warning(this.$t('fileManage.oneFileTips'));
            },
            //保存（或提交）时，先上传文件，再保存（或提交）
            handleUploadSuccess(response, file, fileList) {
                let index = file.name.lastIndexOf(".");
                this.modelData.fileName = file.name
                this.modelData.fileType = file.name.substring(index).replace(".","").toUpperCase()
                this.modelData.fileSize = file.size
                if (fileList.every(file_ => file_.status === "success")) {
                    this.modelSave();
                }
            },

            //确定
            modelSave() {
                let param = {};
                for (let key in this.modelData) {
                    param[key] = this.modelData[key];
                }
                this.modelOptions.modules.map(e=>{
                    if(e.value == param.moduleId){
                        param.moduleName =e.label
                    }
                })
                if (this.modelFlag == 'add') {
                    if (this.fileList.some(f => f.percentage == 0)) {
                        this.$refs.uploadBtn.submit();
                        return;
                    }
                    let files = this.fileList.map(f => {
                        return f.response ? f.response.data[f.name].objectkey : f.url;
                    });
                    param.filePath = files.join(",");
                }

                this.$refs.dialogFrom.validate(valid => {
                    if (valid && this.modelFlag === "add") {
                        addFile(param).then(res => {
                            if (res.code === 200) {
                                this.modelCancel();
                            } else {
                                this.$message({type: "error", message: res.msg});
                            }
                        });
                    }
                });
            },

            //清空弹框内容，关闭弹框并重新刷新列表
            modelCancel() {
                this.modelFlag = null;
                this.clearModelData();
                this.$refs.dialogModel.close();
                //弹框关闭后，重新获取列表
                this.onSubmit();
            },


        }
    };
</script>
<style lang="scss" scoped>

</style>
